from django.http import JsonResponse
from django.views import View

from apps.house.models import House
from apps.order.models import Order
from apps.users.models import User


# from iHome.apps.house.models import HouseImage

from apps.house import models




class HouseYuanView(View):

    def get(self, request, house_id):
        # 测试
        # user = User.objects.get(id=house_id)
        # 获取登录用户
        # user = request.user

        # 获取房屋id
        try:
            house = House.objects.get(id=house_id)
        except:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})
        # 获取房屋表中的所有字段
        house_xq = {
            "hid": house.id,
            "user_id": house.user.id,
            "user_name": house.user.username,
            "user_avatar": house.user.avatar_url if house.user.avatar_url else "",
            "title": house.title,
            "price": house.price,
            "address": house.address,
            "room_count": house.room_count,
            "acreage": house.acreage,
            "unit": house.unit,
            "capacity": house.capacity,
            "beds": house.beds,
            "deposit": house.deposit,
            "min_days": house.min_days,
            "max_days": house.max_days,
        }

        comments = []
        orders = Order.objects.filter(house=house, status="COMPLETE").order_by('-update_time')
        if orders.count() > 30:
            orders = orders[:30]
        for order in orders:
            comment = {
                "comment": order.comment,
                "user_name": order.user.username if order.user.username != order.user.mobile else "匿名用户",  # 发表评论的用户
                "ctime": order.update_time.strftime("%Y-%m-%d %H:%M:%S")  # 评价的时间
            }
            comments.append(comment)
        house_xq["comments"] = comments

        img_urls = []
        for image in house.houseimage_set.all():
            img_urls.append(image.url)
        house_xq["img_urls"] = img_urls

        return JsonResponse({'code': 0, 'errmsg': 'ok!', 'house_xq': house_xq})